import { getProvinces, getCities, getDistricts } from "@/api/system/area";

const state = {
  areaData: {
    provinces: [],
    cities: {},
    districts: {}
  },
  loading: false,
  error: null
}

const mutations = {
  SET_AREA_DATA: (state, data) => {
    state.areaData = data
  },
  SET_LOADING: (state, status) => {
    state.loading = status
  },
  SET_ERROR: (state, error) => {
    state.error = error
  }
}

const actions = {
  // 预加载地区数据
  preloadAreaData({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      try {
        // 如果已经有数据且未过期，直接返回
        const cachedData = localStorage.getItem('areaData')
        if (cachedData) {
          const { data, timestamp } = JSON.parse(cachedData)
          const cacheExpireTime = 24 * 60 * 60 * 1000 // 24小时
          if (Date.now() - timestamp < cacheExpireTime) {
            commit('SET_AREA_DATA', data)
            resolve(data)
            return
          }
        }

        commit('SET_LOADING', true)
        
        // 获取所有省份数据
        const provincesRes = await getProvinces()
        const provinces = provincesRes.data
        
        // 分批获取城市数据
        const batchSize = 5
        const cities = {}
        const districts = {}
        
        for (let i = 0; i < provinces.length; i += batchSize) {
          const batch = provinces.slice(i, i + batchSize)
          const cityPromises = batch.map(province => 
            getCities(province.areaId).then(res => {
              cities[province.areaId] = res.data
              return res.data
            })
          )
          
          await Promise.all(cityPromises)
          
          // 获取区县数据
          for (const province of batch) {
            const provinceCities = cities[province.areaId] || []
            for (const city of provinceCities) {
              const districtsRes = await getDistricts(city.areaId)
              districts[city.areaId] = districtsRes.data
            }
          }
        }
        
        const areaData = {
          provinces,
          cities,
          districts
        }
        
        // 缓存数据
        localStorage.setItem('areaData', JSON.stringify({
          data: areaData,
          timestamp: Date.now()
        }))
        
        commit('SET_AREA_DATA', areaData)
        commit('SET_LOADING', false)
        resolve(areaData)
      } catch (error) {
        commit('SET_ERROR', error)
        commit('SET_LOADING', false)
        reject(error)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 